package com.zhongxi.guoyuan.view;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.bumptech.glide.Glide;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;
import com.zhongxi.guoyuan.OffLineShop.ConnectNet.NetWork;
import com.zhongxi.guoyuan.OffLineShop.UI.OffLineBaseActivity;
import com.zhongxi.guoyuan.OffLineShop.UrlOffLine.RelativeUrl;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.entity.ad.AdResult;
import com.zhongxi.guoyuan.service.LocationService;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.LunBoUtils;
import com.zhongxi.guoyuan.utils.RegularTool;
import com.zhongxi.guoyuan.utils.SpUtils;
import com.zhongxi.guoyuan.utils.ToastUtil;
import com.zhongxi.guoyuan.utils.UiUtils;
import com.zhongxi.guoyuan.widget.view.CountTimerView;

import org.json.JSONObject;

import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

public class WelcomeActivity extends OffLineBaseActivity {

    private static final int PERMISSIONCODE = 115;
    private ImageView iv;

    private CountTimerView circleView;
    private LocationService locationService;

    @Override
    protected void init() {
        super.init();
        //获取全屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_welcome);
    }

    @Override
    protected void initView() {
        super.initView();
        iv = (ImageView) findViewById(R.id.iv);
        circleView = (CountTimerView) findViewById(R.id.circleView);
        circleView.setmProgressType(CountTimerView.ProgressType.COUNT_BACK);
        MyApplication.getInstance().sharedPrefrences.edit().putString("now", String.valueOf(System.currentTimeMillis())).commit();
        MyApplication.getInstance().sharedPrefrences.edit().putString("sk", RegularTool.getRandomString(8)).commit();
        getPermission();
    }

    private void getPermission() {
        AndPermission.with(this).requestCode(PERMISSIONCODE)
                .permission(new String[]{Manifest.permission.READ_PHONE_STATE}, Permission.LOCATION, Permission.CAMERA, Permission.STORAGE)
                .callback(new PermissionListener() {
                    @Override
                    public void onSucceed(int i, @NonNull List<String> list) {
                        TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
                        @SuppressLint("MissingPermission") String szImei = TelephonyMgr.getDeviceId();
                        MyApplication.getInstance().sharedPrefrences.edit().putString("szImei", szImei).commit();  //SSENSOR
                        locationService = MyApplication.getInstance().locationService;
                        locationService.registerListener(mListener);
                        locationService.setLocationOption(locationService.getDefaultLocationClientOption());
                        locationService.start();
                        netWork();
                    }

                    @Override
                    public void onFailed(int i, @NonNull List<String> list) {
                        boolean isopen = true;
                        if (list.size() > 0) {
                            for (int j = 0; j < list.size(); j++) {
                                if (list.get(j).equals(Manifest.permission.READ_PHONE_STATE)) {
                                    ToastUtil.show("没有获取手机当前状态权限,APP无法使用");
                                    isopen = false;
                                }
                            }
                        }
                        if (isopen) {
                            ToastUtil.show("没有获取相应权限,APP内某些功能将无法使用");
                            TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
                            @SuppressLint("MissingPermission") String szImei = TelephonyMgr.getDeviceId();
                            MyApplication.getInstance().sharedPrefrences.edit().putString("szImei", szImei).commit();  //SSENSOR
                            netWork();
                        }
                    }
                })
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int i, Rationale rationale) {
                        rationale.resume();
                    }
                })
                .start();
    }

    private void netWork() {
        unsubscribe();
        mDisposable = NetWork.getOffLineApi().welcomeApi(RelativeUrl.WELCOME + MyApplication.getInstance().getUrl(),
                MyApplication.getInstance().getCheck(false))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<ResponseBody>() {
                    @Override
                    public void accept(ResponseBody responseBody) throws Exception {
                        String mString = responseBody.string();
                        JSONObject jsonObject = new JSONObject(mString);
                        int mCode = jsonObject.optInt("code");
                        if (mCode == 1) {
                            JSONObject mExpressCode = jsonObject.optJSONObject("expressCode");
                            MyApplication.getInstance().sharedPrefrences.edit().putString("logistics", mExpressCode.toString()).commit();
                            unsubscribe();
                            getOtherNet();
                        } else if (mCode == 2816) {
                            logoutDialog();
                        } else {
                            ToastUtil.show(getString(R.string.loseData, mCode));
                            unsubscribe();
                            getOtherNet();
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        ToastUtil.show(getString(R.string.load_error));
                    }
                });
    }

    private void logoutDialog() {
        final AlertDialog mDialog = new AlertDialog.Builder(this).create();
        View view = UiUtils.inflate(R.layout.dialog_logout);
        TextView tv_Iknow = (TextView) view.findViewById(R.id.tv_Iknow);
        tv_Iknow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
                if (null != MyApplication.getInstance().getUserId() || !"".equals(MyApplication.getInstance().getUserId())) {
                    clearAppData();
                }
                unsubscribe();
                getOtherNet();
            }
        });
        mDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (mDialog != null && mDialog.isShowing()) {
                        mDialog.dismiss();
                        if (null != MyApplication.getInstance().getUserId() || !"".equals(MyApplication.getInstance().getUserId())) {
                            clearAppData();
                            finish();
                        }
                    }
                    return true;
                }
                return false;
            }
        });
        mDialog.setCanceledOnTouchOutside(false);
        mDialog.setView(view);
        mDialog.show();
    }

    private void clearAppData() {
        MyApplication.getInstance().sharedPrefrences.edit().putString("phone", "").commit();
        MyApplication.getInstance().sharedPrefrences.edit().putString("userid", "").commit();
        MyApplication.getInstance().sharedPrefrences.edit().putString("username", "").commit();
        MyApplication.getInstance().sharedPrefrences.edit().putString("shopname", "").commit();
        MyApplication.getInstance().sharedPrefrences.edit().putString("rmb", "").commit();
        MyApplication.getInstance().sharedPrefrences.edit().putString("silver", "").commit();
        MyApplication.getInstance().sharedPrefrences.edit().putString("inner", "").commit();
        MyApplication.getInstance().sharedPrefrences.edit().putString("hd", "").commit();
        MyApplication.getInstance().sharedPrefrences.edit().putString("num", "").commit();
        MyApplication.getInstance().sharedPrefrences.edit().putString("avatar", "").commit();
        MyApplication.getInstance().sharedPrefrences.edit().putBoolean("shareHolder", false).commit();
        MyApplication.getInstance().sharedPrefrences.edit().putBoolean("privilege", false).commit();
        MyApplication.getInstance().sharedPrefrences.edit().putBoolean("beneficiary", false).commit();
        MyApplication.getInstance().sharedPrefrences.edit().putBoolean("merchants", false).commit();
        MyApplication.getInstance().sharedPrefrences.edit().putString("appopenid", "").commit();

        MyApplication.getInstance().sharedPrefrences.edit().putString("avatar", "").commit();
        MyApplication.getInstance().sharedPrefrences.edit().putString("rewardName", "").commit();
        MyApplication.getInstance().sharedPrefrences.edit().putString("rewardUserphone", "").commit();
        MyApplication.getInstance().sharedPrefrences.edit().putString("rewardAddress", "").commit();
        MyApplication.getInstance().sharedPrefrences.edit().putString("rewardAddressid", "").commit();
        SpUtils.getInstance().saveSp("shopid", "");
        SpUtils.getInstance().saveSp("mdffline", "");
        SpUtils.getInstance().saveSp("orderid", "");
    }

    private void getOtherNet() {
        mDisposable = NetWork.getOffLineApi().getAdApi(RelativeUrl.AdUrl + MyApplication.getInstance().getUrl(),
                MyApplication.getInstance().getCheck(false), 4)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<AdResult>() {
                    @Override
                    public void accept(AdResult adResult) throws Exception {
                        MyApplication.getInstance().setSpValue(adResult.getSafeobj());
                        if (adResult.getCode() == 1) {
                            if (adResult.getData() != null && adResult.getData().size() > 0) {
                                Glide.with(UiUtils.getContext())
                                        .load(Url.IMG_URL + adResult.getData().get(0).getImage())
                                        .placeholder(R.mipmap.guide).fitCenter().into(iv);
                                //有广告
                                circleView.setVisibility(View.VISIBLE);
                                circleView.start();
                                clickAD(adResult.getData().get(0).getId(), adResult.getData().get(0).getIsvideo(),
                                        adResult.getData().get(0).getUrl(), 4);
                            } else {
                                //无广告
                                circleView.setVisibility(View.GONE);
                                startNextActivity();
                            }
                        } else {
                            ToastUtil.show(getString(R.string.loseData, adResult.getCode()));
                        }

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        ToastUtil.show(getString(R.string.load_error));
                    }
                });
    }

    private void clickAD(final String id, final int isvideo, final String url, final int flag) {
        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(url)) {
                    finish();
                    circleView.stop();
                    LunBoUtils.getInstance(WelcomeActivity.this).lunBoItemClickListener(id, isvideo, url, flag);
                }
            }
        });
    }

    private void startNextActivity() {
        startActivity(new Intent(UiUtils.getContext(), MainHomeActivity.class));
        finish();
    }

    @Override
    protected void initListener() {
        super.initListener();
        circleView.setProgressListener(new CountTimerView.OnProgressListener() {
            @Override
            public void onProgress(int progress) {
                if (progress == 99) {
                    startNextActivity();
                }
            }
        });
    }

    @Override
    protected void onStop() {
        if (locationService!=null) {
            locationService.unregisterListener(mListener); //注销掉监听
            locationService.stop(); //停止定位服务
            if (circleView.isShown()) {
                circleView.stop();
            }
        }
        super.onStop();
    }

    private BDAbstractLocationListener mListener = new BDAbstractLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            if (161 == bdLocation.getLocType()) {  // 定位成功
                MyApplication.getInstance().sharedPrefrences.edit().putString("province", bdLocation.getProvince()).commit();
                MyApplication.getInstance().sharedPrefrences.edit().putString("city", bdLocation.getCity()).commit();
                MyApplication.getInstance().sharedPrefrences.edit().putString("longitude", bdLocation.getLongitude() + "").commit();
                MyApplication.getInstance().sharedPrefrences.edit().putString("latitude", bdLocation.getLatitude() + "").commit();
            }
            double latitude = bdLocation.getLatitude();    //获取纬度信息
            double longitude = bdLocation.getLongitude();    //获取经度信息
            float radius = bdLocation.getRadius();    //获取定位精度，默认值为0.0f

            String coorType = bdLocation.getCoorType();
            //获取经纬度坐标类型，以LocationClientOption中设置过的坐标类型为准

            int errorCode = bdLocation.getLocType();
            //获取定位类型、定位错误返回码，具体信息可参照类参考中BDLocation类中的说明
            String addr = bdLocation.getAddrStr();    //获取详细地址信息
            String country = bdLocation.getCountry();    //获取国家
            String province = bdLocation.getProvince();    //获取省份
            String city = bdLocation.getCity();    //获取城市
            String district = bdLocation.getDistrict();    //获取区县
            String street = bdLocation.getStreet();    //获取街道信息
            StringBuffer mSb = new StringBuffer();
            mSb.append("latitude:" + latitude);
            mSb.append("\nlongitude:" + longitude);
            mSb.append("\nradius:" + radius);
            mSb.append("\ncoorType:" + coorType);

            mSb.append("\nerrorCode:" + errorCode);
            mSb.append("\naddr:" + addr);
            mSb.append("\ncountry:" + country);
            mSb.append("\nprovince:" + province);
            mSb.append("\ncity:" + city);
            mSb.append("\ndistrict:" + district);
            mSb.append("\nstreet:" + street);

            System.out.println("sb==" + mSb.toString());

            //保存定位信息
        }
    };
}
